package com.example.joblinker.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.joblinker.common.Result;
import com.example.joblinker.entity.Job;
import com.example.joblinker.entity.JobApplication;
import com.example.joblinker.mapper.JobApplicationMapper;
import com.example.joblinker.mapper.JobMapper;
import com.example.joblinker.util.JwtUtil;
import com.example.joblinker.dto.ApplicationStatsDTO;
import com.example.joblinker.service.ApplicationService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 职位申请记录控制器
 */
@RestController
@RequestMapping("/applications")
public class ApplicationController {

    @Resource
    private JobApplicationMapper jobApplicationMapper;

    @Resource
    private JobMapper jobMapper;

    @Resource
    private JwtUtil jwtUtil;

    @Autowired
    private ApplicationService applicationService;

    /**
     * 获取用户的职位申请记录
     */
    @GetMapping("/user")
    public Result<Page<Map<String, Object>>> getUserApplications(
            HttpServletRequest request,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer status) {
        Long userId = jwtUtil.getUserIdFromRequest(request);
        
        // 构建查询条件
        Page<JobApplication> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<JobApplication> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(JobApplication::getUserId, userId);
        
        // 添加状态筛选条件
        if (status != null) {
            wrapper.eq(JobApplication::getStatus, status);
        }
        
        // 按时间倒序排序
        wrapper.orderByDesc(JobApplication::getUpdateTime);
        
        // 执行分页查询
        Page<JobApplication> applicationPage = jobApplicationMapper.selectPage(pageParam, wrapper);
        
        // 转换为前端需要的格式，附带职位和公司信息
        Page<Map<String, Object>> resultPage = new Page<>();
        resultPage.setTotal(applicationPage.getTotal());
        resultPage.setCurrent(applicationPage.getCurrent());
        resultPage.setSize(applicationPage.getSize());
        
        // 创建新的ArrayList存储转换后的记录
        List<Map<String, Object>> records = new ArrayList<>();
        
        // 转换记录格式
        applicationPage.getRecords().forEach(application -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", application.getId());
            map.put("status", application.getStatus());
            map.put("applyTime", application.getCreateTime());
            map.put("updateTime", application.getUpdateTime());
            
            // 获取职位信息
            Job job = jobMapper.selectById(application.getJobId());
            if (job != null) {
                map.put("jobId", job.getId());
                map.put("jobTitle", job.getTitle());
                map.put("companyName", job.getCompanyName());
                map.put("companyLogo", job.getCompanyLogo());
            }
            
            records.add(map);
        });
        
        resultPage.setRecords(records);
        
        return Result.success(resultPage);
    }

    /**
     * 获取申请详情
     */
    @GetMapping("/{id}")
    public Result<Map<String, Object>> getApplicationDetail(
            HttpServletRequest request,
            @PathVariable Long id) {
        Long userId = jwtUtil.getUserIdFromRequest(request);
        
        // 查询申请记录
        JobApplication application = jobApplicationMapper.selectById(id);
        if (application == null) {
            return Result.error("申请记录不存在");
        }
        
        // 检查权限
        if (!application.getUserId().equals(userId)) {
            return Result.error("无权访问此申请记录");
        }
        
        // 获取职位信息
        Job job = jobMapper.selectById(application.getJobId());
        
        // 构建详情信息
        Map<String, Object> detail = new HashMap<>();
        detail.put("id", application.getId());
        detail.put("status", application.getStatus());
        detail.put("statusText", getStatusText(application.getStatus()));
        detail.put("applyTime", application.getCreateTime());
        detail.put("updateTime", application.getUpdateTime());
        detail.put("processNote", application.getProcessNote());
        
        // 添加职位相关信息
        if (job != null) {
            detail.put("jobId", job.getId());
            detail.put("jobTitle", job.getTitle());
            detail.put("companyName", job.getCompanyName());
            detail.put("companyLogo", job.getCompanyLogo());
            detail.put("salary", job.getSalary());
            detail.put("city", job.getCity());
            detail.put("requirement", job.getRequirement());
        }
        
        return Result.success(detail);
    }

    /**
     * 更新申请状态（只能取消申请）
     */
    @PutMapping("/{id}/status")
    public Result<Void> updateApplicationStatus(
            HttpServletRequest request,
            @PathVariable Long id,
            @RequestBody StatusUpdateWrapper statusWrapper) {
        Long userId = jwtUtil.getUserIdFromRequest(request);
        
        // 查询申请记录
        JobApplication application = jobApplicationMapper.selectById(id);
        if (application == null) {
            return Result.error("申请记录不存在");
        }
        
        // 检查权限
        if (!application.getUserId().equals(userId)) {
            return Result.error("无权操作此申请记录");
        }
        
        // 用户只能将状态修改为已取消(4)
        if (statusWrapper.getStatus() != 4) {
            return Result.error("用户只能取消申请");
        }
        
        // 更新状态
        application.setStatus(statusWrapper.getStatus());
        application.setUpdateTime(LocalDateTime.now());
        application.setProcessNote(statusWrapper.getNote());
        
        jobApplicationMapper.updateById(application);
        
        return Result.success();
    }

    /**
     * 将状态值转换为文本
     */
    private String getStatusText(Integer status) {
        switch (status) {
            case 0:
                return "待处理";
            case 1:
                return "已查看";
            case 2:
                return "待面试";
            case 3:
                return "已通过";
            case 4:
                return "已拒绝";
            case 5:
                return "已取消";
            default:
                return "未知";
        }
    }

    /**
     * 状态更新包装类
     */
    @Data
    public static class StatusUpdateWrapper {
        private Integer status;
        private String note;
    }

    /**
     * 获取职位申请统计数据
     */
    @GetMapping("/stats/{jobId}")
    public Result<ApplicationStatsDTO> getJobApplicationStats(@PathVariable Long jobId) {
        try {
            ApplicationStatsDTO stats = applicationService.getJobApplicationStats(jobId);
            return Result.success(stats);
        } catch (Exception e) {
            return Result.error("获取职位申请统计失败: " + e.getMessage());
        }
    }
} 